package com.example.liyuehui.processerlib;

import com.example.liyuehui.annotationlib.Id;
import com.example.liyuehui.annotationlib.Persistent;
import com.example.liyuehui.annotationlib.Property;

import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.Name;
import javax.lang.model.element.TypeElement;

import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.Set;

@SupportedSourceVersion(SourceVersion.RELEASE_8)
@SupportedAnnotationTypes({"com.example.liyuehui.annotationlib.Id",
		"com.example.liyuehui.annotationlib.Persistent", "com.example.liyuehui.annotationlib.Property"})
public class HibernateAnnotation extends AbstractProcessor {
	@Override
	public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
		PrintStream ps = null;
		System.out.println("begin process");
		try {
			for (Element t : roundEnv.getElementsAnnotatedWith(Persistent.class)) {
				Name className = t.getSimpleName();
				Persistent persistent = t.getAnnotation(Persistent.class);
				ps = new PrintStream(new FileOutputStream(className + ".hbm.xml"));
				ps.println("<?xml version=\"1.0\"?>");
				ps.println("<!DOCTYPE hibernate-mapping PUBKC");
				ps.println("    \"http://www.hibernamte.org/dtd/" + "hibernate-mapping-3.0.dtd\">");
				ps.println("<hibernate-mapping>");
				ps.println("    <class name=\"" + t + "\"");
				ps.println("        table=\"" + persistent.table() + "\">");
				for (Element f : t.getEnclosedElements()) {
					if (f.getKind() == ElementKind.FIELD) {
						Id id = f.getAnnotation(Id.class);
						if (id != null) {
							ps.println("          <id name=\""
									+ f.getSimpleName()
									+ "\" column=\"" + id.column()
									+ "\" type=\"" + id.type() + "\">");
							ps.println("          </id>");
							ps.println("          <generator class=\"" + id.generator() + "\"" + "/>");
						}

						Property p = f.getAnnotation(Property.class);
						if (p != null) {
							ps.println("          <property name=\""
									+ f.getSimpleName()
									+ "\" column=\"" + p.column()
									+ "\" type=\"" + p.type() + "\"/>");

						}
					}
				}
				ps.println("    </class>");
				ps.println("</hibernate-mapping>");
			}
		} catch (Exception excetion) {
			excetion.printStackTrace();
		} finally {
			if (ps != null) {
				try {
					ps.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			System.out.println("end process");
		}
		return true;
	}
}
